{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "is_executing": true
    },
    "ExecuteTime": {
     "start_time": "2025-06-13T02:17:25.479733Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import fetch_openml\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
    "import seaborn as sns\n",
    "\n",
    "# 加载MNIST数据集\n",
    "def load_mnist_data():\n",
    "    print(\"正在加载MNIST数据集...\")\n",
    "    # 从OpenML获取MNIST数据集（70,000样本，784特征）\n",
    "    X, y = fetch_openml('mnist_784', version=1, return_X_y=True, parser='auto')\n",
    "    # 将数据转换为数值类型\n",
    "    X = X.astype(np.float64)\n",
    "    y = y.astype(np.int64)\n",
    "    print(f\"数据集加载完成，样本数: {X.shape[0]}, 特征数: {X.shape[1]}\")\n",
    "    return X, y\n",
    "\n",
    "# 数据预处理\n",
    "def preprocess_data(X, y, test_size=0.2, random_state=42):\n",
    "    print(\"正在预处理数据...\")\n",
    "    # 划分训练集和测试集\n",
    "    X_train, X_test, y_train, y_test = train_test_split(\n",
    "        X, y, test_size=test_size, random_state=random_state, stratify=y\n",
    "    )\n",
    "    # 标准化像素值到[0,1]区间\n",
    "    X_train = X_train / 255.0\n",
    "    X_test = X_test / 255.0\n",
    "    print(f\"训练集大小: {X_train.shape[0]}, 测试集大小: {X_test.shape[0]}\")\n",
    "    return X_train, X_test, y_train, y_test\n",
    "\n",
    "# 训练朴素贝叶斯模型\n",
    "def train_naive_bayes(X_train, y_train):\n",
    "    print(\"正在训练高斯朴素贝叶斯模型...\")\n",
    "    # 初始化高斯朴素贝叶斯分类器\n",
    "    gnb = GaussianNB()\n",
    "    # 训练模型\n",
    "    gnb.fit(X_train, y_train)\n",
    "    print(\"模型训练完成\")\n",
    "    return gnb\n",
    "\n",
    "# 评估模型\n",
    "def evaluate_model(model, X_test, y_test):\n",
    "    print(\"正在评估模型...\")\n",
    "    # 预测测试集\n",
    "    y_pred = model.predict(X_test)\n",
    "    # 计算准确率\n",
    "    accuracy = accuracy_score(y_test, y_pred)\n",
    "    print(f\"模型准确率: {accuracy:.4f}\")\n",
    "\n",
    "    # 生成分类报告\n",
    "    report = classification_report(y_test, y_pred)\n",
    "    print(\"分类报告:\\n\", report)\n",
    "\n",
    "    # 绘制混淆矩阵\n",
    "    cm = confusion_matrix(y_test, y_pred)\n",
    "    plt.figure(figsize=(10, 8))\n",
    "    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
    "                xticklabels=np.unique(y_test),\n",
    "                yticklabels=np.unique(y_test))\n",
    "    plt.xlabel('预测标签')\n",
    "    plt.ylabel('真实标签')\n",
    "    plt.title('混淆矩阵')\n",
    "    plt.savefig('confusion_matrix.png')\n",
    "    plt.close()\n",
    "\n",
    "    return accuracy, y_pred\n",
    "\n",
    "# 可视化样本和预测结果\n",
    "def visualize_results(X_test, y_test, y_pred, n_samples=10):\n",
    "    print(f\"可视化{ n_samples }个样本的预测结果...\")\n",
    "    plt.figure(figsize=(15, 4))\n",
    "\n",
    "    for i in range(n_samples):\n",
    "        plt.subplot(1, n_samples, i+1)\n",
    "        # 重塑为28x28图像\n",
    "        img = X_test[i].reshape(28, 28)\n",
    "        plt.imshow(img, cmap='gray')\n",
    "        # 设置标题：真实标签 vs 预测标签\n",
    "        plt.title(f\"真实: {y_test[i]}\\n预测: {y_pred[i]}\")\n",
    "        plt.axis('off')\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.savefig('prediction_examples.png')\n",
    "    plt.close()\n",
    "    print(\"可视化结果已保存\")\n",
    "\n",
    "# 主函数\n",
    "def main():\n",
    "    # 加载数据\n",
    "    X, y = load_mnist_data()\n",
    "\n",
    "    # 预处理数据\n",
    "    X_train, X_test, y_train, y_test = preprocess_data(X, y)\n",
    "\n",
    "    # 训练模型\n",
    "    model = train_naive_bayes(X_train, y_train)\n",
    "\n",
    "    # 评估模型\n",
    "    accuracy, y_pred = evaluate_model(model, X_test, y_test)\n",
    "\n",
    "    # 可视化结果\n",
    "    visualize_results(X_test, y_test, y_pred)\n",
    "\n",
    "    print(f\"高斯朴素贝叶斯模型在MNIST数据集上的最终准确率: {accuracy:.4f}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正在加载MNIST数据集...\n"
     ]
    }
   ],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
